package sms

import (
	"api/pkg/logger"
	"encoding/json"
	"errors"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
)

type Aliyun struct{}

func (Aliyun) Send(phone string, message Message, configs map[string]string) bool {
	var err error
	logger.DebugJSON("短信[阿里云]", "配置信息", configs)
	config := &openapi.Config{
		// 您的 AccessKey ID
		AccessKeyId: tea.String(configs["access_key_id"]),
		// 您的 AccessKey Secret
		AccessKeySecret: tea.String(configs["access_key_secret"]),
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	client := &dysmsapi20170525.Client{}
	client, err = dysmsapi20170525.NewClient(config)
	if err != nil {
		logger.ErrorString("短信[阿里云]", "解析绑定失败", err.Error())
		return false
	}
	data, err := json.Marshal(message.Data)
	logger.LogIf(err)
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{

		SignName:      tea.String(configs["sign_name"]), //模板名称
		TemplateCode:  tea.String(message.Template),     //发送模板
		PhoneNumbers:  tea.String(phone),                //发送电话
		TemplateParam: tea.String(string(data)),         //发送验证码
	}
	logger.DebugJSON("短信[阿里云]", "发送信息", sendSmsRequest)
	runtime := &util.RuntimeOptions{}
	err = func() (e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		result, err := client.SendSmsWithOptions(sendSmsRequest, runtime)
		if err != nil {
			return err
		}
		logger.DebugJSON("短信[阿里云]", "响应结果", result)
		if *result.Body.Code != "OK" {
			return errors.New(*result.Body.Message)
		}
		return nil
	}()
	if err != nil {
		var sdkerr = &tea.SDKError{}
		if t, ok := err.(*tea.SDKError); ok {
			sdkerr = t
		} else {
			sdkerr.Message = tea.String(err.Error())
		}
		// 如有需要，请打印 error
		logger.ErrorString("短信[阿里云]", "短信发送失败", *util.AssertAsString(sdkerr.Message))
	}
	return err == nil
}
